package com.filldream.fastboot.common.util;

import com.filldream.fastboot.common.exception.GlobalException;
import com.filldream.fastboot.common.entity.ErrorCode;
import freemarker.template.Configuration;
import freemarker.template.Template;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * @author RickSun && iFillDream
 * @version 1.0
 * @data 2020-06-05 9:47
 * @description Office Word工具
 */
public class WordUtil {

    /**
     * 根据模板导出Word文档
     * 导出步骤：
     *  1、设计好模板
     *  2、编写替换符，如:${name}，若是图片请先填充示例图片
     *  3、另存为xml文件
     *  4、修改为ftl文件
     *  5、若有替换图片则将原有的示例图片的base64字符串替换为替换符号
     *  注意：图片要转成base64字符串的
     * @param url   模板url
     * @param dataMap   数据
     * @param fileName  导出的文件名，默认为uuid
     * @param response
     */
    public static  void createDoc(String url,Map<String,Object> dataMap,String fileName,HttpServletResponse response){
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        String templateName = url.substring(url.lastIndexOf("/")).substring(1);
        url =  url.substring(0,url.lastIndexOf("/"));
        RemoteTemplateLoader templateLoader = new RemoteTemplateLoader(url);
        configuration.setTemplateLoader(templateLoader);

        fileName = FileIOUtil.getFileChineseName(fileName);

        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".doc");
        Writer out = null;
        try {
            BufferedOutputStream bus = new BufferedOutputStream(response.getOutputStream());
            out = new BufferedWriter(new OutputStreamWriter(bus,"UTF-8"));
            Template t = configuration.getTemplate(templateName,"UTF-8");
            t.process(dataMap, out);
        } catch (Exception e) {
            throw new GlobalException(ErrorCode.DOWNLOAD_ERR.reMsg(":doc"),e,true);
        }

    }






}
